<#assign title="资源管理-角色"/>
<#include "/layout/layout.html"/>
<#macro link>
</#macro>

<#macro content>
    <div class="container-fluid" style="margin-top: 10px">
        <div class="row">
            <div class="col-md-12">
                <ul class="nav nav-tabs">
                    <li role="presentation"  data-tabid="system"><a href="javascript:;"><span class="glyphicon glyphicon-apple" aria-hidden="true"></span>系统默认角色</a></li>
                    <li role="presentation" class="active" data-tabid="custom"><a href="javascript:;" ><span class="glyphicon glyphicon-leaf" aria-hidden="true"></span>自定义角色</a></li>
                </ul>
                <div>
                    <div data-tabid="system" style="display: none">
                        <table id="sysTable"></table>
                    </div>
                    <div data-tabid="custom">
                        <div id="toolbar">
                            <a href="javascript:void(0);" class="btn btn-primary" id="addRole" ><span class="glyphicon glyphicon-plus"></span>新增</a>
                            <a href="javascript:void(0);" class="btn btn-default" id="deleteRoles"><span class="glyphicon glyphicon-minus"></span>删除</a>
                        </div>
                        <table id="cusTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="addModel" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">新增角色</h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-2"><label for="addRoleName"><span class="hd-span">角色名称</span></label></div>
                        <div class="col-md-10"><input type="text" id="addRoleName" class="hd-input-form form-control" ></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="addRoleCode"><span class="hd-span">角色代码</span></label></div>
                        <div class="col-md-10"><input type="text" id="addRoleCode" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="addRoleCode"><span class="hd-span">组织代码</span></label></div>
                        <div class="col-md-10"><input type="text" id="addOrgCode" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><span class="hd-span">角色权限</span></div>
                        <div class="col-md-10" style="height: 270px;overflow: auto;margin-top: 5px">
                            <ul id="addAuthorizeTree" class="ztree"></ul>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" id="addRoleDo" class="btn btn-primary">确认</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    <div id="editModel" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">修改角色</h4>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="editRoleId" value="">
                    <div class="row">
                        <div class="col-md-2"><label for="editRoleName"><span class="hd-span">角色名称</span></label></div>
                        <div class="col-md-10"><input type="text" id="editRoleName" class="hd-input-form form-control" ></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="editRoleCode"><span class="hd-span">角色代码</span></label></div>
                        <div class="col-md-10"><input type="text" id="editRoleCode" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="editOrgCode"><span class="hd-span">组织代码</span></label></div>
                        <div class="col-md-10"><input type="text" id="editOrgCode" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><span class="hd-span">角色权限</span></div>
                        <div class="col-md-10" style="height: 270px;overflow: auto;margin-top: 5px">
                            <ul id="editAuthorizeTree" class="ztree"></ul>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" id="editRoleDo" class="btn btn-primary">确认</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
</#macro>

<#macro script>
    <script type="text/javascript">
        $(function () {
            const addTreeId = "addAuthorizeTree";
            const editTreeId="editAuthorizeTree";
            const setting = {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                }, check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: {"Y": "ps", "N": "ps"}
                }
            };
            //获取所有自定义角色
            const $cusTable = $("#cusTable").bootstrapTable({
                url: rootPath + "/role/all/custom",         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                height: 460,
                showRefresh: true,
                showColumns: true,
                search: true,
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                strictSearch: true,
                clickToSelect: true,                //是否启用点击选中行
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                columns: [{
                    checkbox: true,
                }, {
                    field: 'roleName',
                    sortable: true,
                    title: '角色代码'
                }, {
                    field: 'roleRealName',
                    sortable: true,
                    title: '角色名称'
                }, {
                    field: 'orgCode',
                    sortable: true,
                    title: '组织代码'
                }, {
                    title: '操作',
                    clickToSelect: false,
                    formatter: function (v, r,i) {
                        return "<button name='edit' data-rolerealname='"+r.roleRealName+"' data-orgcode='"+r.orgCode+"' data-rolename='"+r.roleName+"' data-roleid='" + r.roleId + "' class='btn btn-default btn-xs'>编辑</button>" +
                            "<button name='delete' data-roleid='" +r.roleId + "' class='btn btn-default btn-xs'>删除</button>"
                    }
                }]
            });
            //获取系统默认角色
            const $sysTable = $("#sysTable").bootstrapTable({
                url: rootPath + "/role/all/system",         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                height: 400,
                showRefresh: true,
                showColumns: true,
                search: true,
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                strictSearch: true,
                clickToSelect: true,                //是否启用点击选中行
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                columns: [{
                    field: 'roleName',
                    sortable: true,
                    title: '角色代码'
                }, {
                    field: 'roleRealName',
                    sortable: true,
                    title: '角色名称'
                }, {
                    field: 'orgCode',
                    sortable: true,
                    title: '组织代码'
                }]
            });
            //自定义角色中的编辑按钮事件
            $("#cusTable").on("click","button[name='edit']",function (e) {
                let roleId=$(this).data("roleid");
                $('#editRoleId').val(roleId);
                $('#editRoleName').val($(this).data("rolerealname"));
                $("#editRoleCode").val($(this).data("rolename"));
                $("#editOrgCode").val($(this).data("orgcode"));
                $.IOQuery ({
                    url:rootPath+"/role/all/permission",
                    type:'get',
                    data:{roleId:roleId},
                    success:function (data) {
                        let zTreeObj;
                        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
                        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
                        zTreeObj = $.fn.zTree.init($("#"+editTreeId), setting, data);
                        $.fn.zTree.getZTreeObj(editTreeId).expandAll(true);
                    }
                });
                $('#editModel').modal('show');
            });
            //单项删除按钮事件
            $("#cusTable").on("click","button[name='delete']",function (e) {
                let roleId = $(this).data("roleid");
                let list = [];
                list.push(roleId);
                deleteRole(list);
            });
            //批量删除按钮事件
            $("#deleteRoles").click(function () {
                let list=$cusTable.bootstrapTable("getSelections").map(function (m) {
                    return m.roleId;
                });
                deleteRole(list);
            });
            $("#editRoleDo").click(function () {
                let params={};
                let authorizeList = $.fn.zTree.getZTreeObj(editTreeId).getChangeCheckedNodes();
                params.updateAddAuthorize=authorizeList.map(function (m) {
                    return {id:m.id,checked:m.checked};
                });
                params.roleId=$("#editRoleId").val();
                params.roleRealName=$("#editRoleName").val();
                params.orgCode =$("#editOrgCode").val();
                params.roleCode =$("#editRoleCode").val();
                $.IOQuery ({
                    url:rootPath+"/role/update",
                    type:"post",
                    contentType:"application/json; charset=utf-8",
                    data:JSON.stringify(params),
                    success:function (data) {
                        if (data.code==='200'){
                            $cusTable.bootstrapTable('refresh');
                            swal("更新角色成功","","success");
                        }else{
                            swal("更新角色失败",data.msg,"error");
                        }
                    }
                })
            });
            //新增角色的事件
            $("#addRole").click(function () {
                loadPermission();
                $('#addModel').modal('show');
            });
            //执行新增角色的事件
            $("#addRoleDo").click(function () {
                let params = {};
                let authorizeList = $.fn.zTree.getZTreeObj(addTreeId).getChangeCheckedNodes();
                params.needAddAuthorize=authorizeList.map(function (m) {
                    return m.id;
                });
                params.roleRealName=$("#addRoleName").val();
                params.roleCode =$("#addRoleCode").val();
                params.orgCode =$("#addOrgCode").val();
                $.IOQuery({
                    url:rootPath+"/role/create",
                    type:"post",
                    data:JSON.stringify(params),
                    contentType:"application/json; charset=utf-8",
                    success:function (data) {
                        if (data.code==='200'){
                            $cusTable.bootstrapTable('refresh');
                            $('#addModel').modal('hide');
                            $("#addRoleName").val('');
                            $("#addRoleCode").val('');
                            $("#addOrgCode").val('');
                            swal("新增角色成功","","success");
                        }else{
                            swal("新增角色失败",data.msg,"error");
                        }
                    }
                })
            });

            $("li[data-tabid]").click(function () {
                $id= $(this).data("tabid");
                $("li[data-tabid]").removeClass("active");
                $(this).addClass("active");
                $("div[data-tabid]").hide();
                $("div[data-tabid='"+$id+"']").show();
            });
            function loadPermission() {
                $.IOQuery ({
                    url:rootPath+"/role/all/permission",
                    type:'get',
                    success:function (data) {
                        let zTreeObj;
                        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
                        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
                        zTreeObj = $.fn.zTree.init($("#"+addTreeId), setting, data);
                        $.fn.zTree.getZTreeObj(addTreeId).expandAll(true);
                    }
                })
            }

            function deleteRole(list) {
                if (list.length>0) {
                    swal({
                            title: "确定删除角色?",
                            text: "",
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonColor: "#DD6B55",
                            confirmButtonText: "delete",
                            closeOnConfirm: false,
                            showLoaderOnConfirm: true
                        },
                        function () {
                            $.IOQuery({
                                url: rootPath + "/role/delete",
                                type: 'post',
                                data: JSON.stringify(list),
                                contentType: "application/json; charset=utf-8",
                                success: function (data) {
                                    if (data.code === '200') {
                                        $cusTable.bootstrapTable('refresh');
                                        swal("删除角色成功", "", "success");
                                    } else {
                                        swal("删除角色失败", data.msg, "error");
                                    }
                                }
                            });
                        });
                }else {
                    swal("请选择至少一个角色","","error");
                }

            }
        })
    </script>
</#macro>
